import { t } from 'i18next'
import React, { forwardRef, ReactNode, useEffect, useImperativeHandle } from 'react'
import { StyledVmpPoll } from './style'
import { Select, InputNumber, CheckBox } from '@kedacom/react-next'

import { fetchGetPollPlanDetail, fetchGetPollPlanList } from '@/api/create/vmp'
import { useRequest } from 'ahooks'
import { useCreateContentStore } from '../../../store'
import LabelWrap from '../../../components/LabelWrap'
import CreateMember from '../../../components/CreateMember'
import { useBasicInfoStore } from '../../basicInfo/store'
import { Alert } from '@/components/Alert'
import { useMeetingVmpStore } from '../store'
import shallow from 'zustand/shallow'
import { setVmpPollList } from '../../../store.combine'
import { initPollData } from '../store.combine'
import { PollRef } from './interface'

export interface VmpPollProps {
	// pollData: Vmp['poll'] | null
	children?: ReactNode
}

const pollIntervalOptions = [
	{ label: t('快（15s）'), value: 15 },
	{ label: t('中（30s）'), value: 30 },
	{ label: t('慢（60s）'), value: 60 },
	{ label: t('自定义'), value: 0 },
]
const VmpPoll = forwardRef((props: VmpPollProps, ref: React.Ref<PollRef>) => {
	const { preKey, isTemplate, _container } = useCreateContentStore(
		(state) => ({ preKey: state.preKey, isTemplate: state.isTemplate, _container: state._container }),
		shallow
	)
	const repeat = useBasicInfoStore((state) => state.repeat)
	// const { pollData } = props
	// const [planOptions, setPlanOptions] = useState<Array<{ label: string; value: string }>>([
	// 	{ label: t('不使用预案'), value: '0' },
	// ])
	// const [planValue, setPlanValue] = useState('0')
	// const [pollIntervalOptionsVal, setPollIntervalOptionsVal] = useState(30)
	// const [pollInterval, setPollInterval] = useState('5')
	// const [pollTimes, setPollTimes] = useState('')
	// const [unlimited, setUnlimited] = useState(true)
	// const [members, setMembers] = useState<Array<UserEntity>>([])
	// const [pollMembers, setPollMembers] = useState<Mt[]>([])
	/**第一步:请求轮询预案数据*/
	const { data: planList } = useRequest(() => fetchGetPollPlanList(preKey, isTemplate))
	const {
		update,
		setBatchPollParams,
		pollPlanOptions,
		pollPlanValue,
		pollIntervalOptionsVal,
		pollInterval,
		pollTimes,
		unlimited,
		pollPlanName,
		members,
	} = useMeetingVmpStore(
		(state) => ({
			members: state.pollMembers,
			pollPlanName: state.pollPlanName,
			pollInterval: state.pollInterval,
			pollIntervalOptionsVal: state.pollIntervalOptionsVal,
			pollPlanOptions: state.pollPlanOptions,
			pollPlanValue: state.pollPlanValue,
			pollTimes: state.pollTimes,
			unlimited: state.unlimited,
			update: state.update,
			setBatchPollParams: state.setBatchPollParams,
		}),
		shallow
	)
	/**第二步:设置轮询预案下拉列表*/
	useEffect(() => {
		if (planList && planList.success) {
			let arr = planList.data ? planList.data.map((item) => ({ label: item.name, value: item.id })) : []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			// setPlanOptions(arr)
			update({ pollPlanOptions: arr })
		}
	}, [planList])
	/**第三步:设置预案值*/
	useEffect(() => {
		// setPlanValue(pollPlanOptions.find((item) => item.label === pollData?.name)?.value ?? '0')
		update({ pollPlanValue: pollPlanOptions.find((item) => item.label === pollPlanName)?.value ?? '0' })
	}, [pollPlanName, pollPlanOptions])

	const changePlan = async (id: string) => {
		// setPlanValue(id)
		update({ pollPlanValue: id })
		if (id === '0') {
			initPollData(null)
			return
		}
		fetchGetPollPlanDetail(preKey, isTemplate, id).then((res) => {
			if (res.success) {
				initPollData(res)
			} else {
				initPollData(null)
			}
		})
	}

	useImperativeHandle(ref, () => ({
		testValue() {
			if (pollIntervalOptionsVal === 0) {
				if (pollInterval === '') {
					Alert(t('请设置轮询间隔'))
					return false
				} else if (Number(pollInterval) < 5 || Number(pollInterval) > 7200) {
					Alert(t('轮询间隔应为5~7200秒'))
					return false
				}
			}
			if (!unlimited) {
				if (pollTimes === '') {
					Alert(t('请设置轮询次数'))
					return false
				} else if (Number(pollTimes) < 1 || Number(pollTimes) > 9999) {
					Alert(t('轮询次数应为1~9999次'))
					return false
				}
			}
			if (members.length === 0) {
				Alert(t('批量轮询列表不能为空'))
				return false
			}
			return true
		},
		getValue() {
			return {
				id: '',
				mode: 1,
				name:
					pollPlanValue === '0'
						? ''
						: pollPlanOptions.find((item) => item.value === pollPlanValue)?.label ?? '',
				keep_time: pollIntervalOptionsVal !== 0 ? pollIntervalOptionsVal : Number(pollInterval),
				num: unlimited ? 0 : Number(pollTimes),
				members: members.map((item) => {
					return {
						account: item.account,
						account_type: item.account_type,
						name: item.name,
						parent_id: item.parent_id,
						conf_e164: item.conf_e164 || item.parent_id || '',
					}
				}),
			}
		},
	}))
	return (
		<StyledVmpPoll>
			{!repeat && (
				<LabelWrap label={t('轮询预案')} className="line_wrap_vmp">
					<Select
						container={() => _container}
						options={pollPlanOptions}
						value={pollPlanValue}
						onClick={(e, v) => changePlan(v)}
					/>
				</LabelWrap>
			)}
			<LabelWrap label={t('轮询间隔')} className="line_wrap_vmp">
				<Select
					container={() => _container}
					width={100}
					options={pollIntervalOptions}
					value={pollIntervalOptionsVal}
					onChange={(e, v) => {
						// setPollIntervalOptionsVal(v)
						update({ pollIntervalOptionsVal: v, pollInterval: '5' })
						// setPollInterval('5')
					}}
				/>
				{pollIntervalOptionsVal === 0 && (
					<div className="seconds">
						<div className="seconds_content">
							<InputNumber
								width={80}
								value={pollInterval}
								onChange={(e, v) => update({ pollInterval: v })}
								maxLength={4}
							/>
							<span className="msg">{t('5~7200秒')}</span>
						</div>
						{pollInterval && (Number(pollInterval) < 5 || Number(pollInterval) > 7200) && (
							<div className="err_msg">{t('轮询间隔为5~7200秒')}</div>
						)}
					</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('轮询次数')} className="line_wrap_vmp poll_num">
				<div className="poll_num_content">
					<InputNumber
						width={80}
						disabled={unlimited}
						value={pollTimes}
						onChange={(e, val) => update({ pollTimes: val })}
						maxLength={4}
					/>
					<span className={`${unlimited ? 'disabled' : ''} msg`}>{t('1~9999次')}</span>
					<CheckBox
						className="unlimited"
						checked={unlimited}
						onChange={(e, val) => update({ unlimited: val })}
					>
						{t('不限次数')}
					</CheckBox>
				</div>
				{!unlimited && pollTimes && (Number(pollTimes) < 1 || Number(pollTimes) > 9999) && (
					<div className="err_msg">{t('轮询次数为1~9999次')}</div>
				)}
			</LabelWrap>
			<LabelWrap label={t('轮询方列表')} className="line_wrap_vmp line_wrap_vmp_member ">
				<CreateMember
					title={t('已选')}
					width={540}
					height={320}
					list={members}
					setOuterList={(h, type) => {
						if (type === 'drop') {
							setVmpPollList(h)
						} else {
							setBatchPollParams({ members: h })
						}
					}}
					isHideOrder={false}
				></CreateMember>
			</LabelWrap>
		</StyledVmpPoll>
	)
})
export default VmpPoll
